package utils
{
	import flash.utils.ByteArray;

	public class RC4Util
	{
		/**
		 * 取得RC4 Keys
		 * @param keys 源keys
		 * @return 返回生成完成的keys
		 */
		public static function getKey(keys:ByteArray):Array
		{
			var box:Array = new Array(256);
			var i:int = 0;
			var x:int = 0;
			var t:int = 0;
			var l:int = keys.length;
			
			for(i=0; i<256; i++){
				box[i] = i;
			}
			
			for(i=0; i<256; i++){
				x = (x+box[i]+keys[i%l]) % 256;
				t = box[x];
				box[x] = box[i];
				box[i] = t;
			}
			return box;
		}
		
		/**
		 * RC4加解密
		 * @param data 加解密源数据
		 * @param key RC4 Keys
		 * @return 返回成功加解密后的数据
		 */
		public static function crypto(data:ByteArray, key:Array):ByteArray
		{
			var t:int;
			var o:int;
			var i:int=0;
			var j:int = 0;
			var l:int = data.length;
			var keys:Array = key.slice(0, 256);
			for(var c:int=0; c<l; c++){
				i = (i+1) % 256;
				j = (j+keys[i]) % 256;
				
				t = keys[j];
				keys[j] = keys[i];
				keys[i] = t;
				
				o = keys[(keys[i] + keys[j]) % 256];
				data[c] = (data[c] ^ o);
			}
			return data;
		}
	}
}